<?php

namespace Qy\Controller;

use Common\Controller\BaseController;
use vod\Request\V20170321 as vod;

class CurriculumController extends BaseController {

    /**
     * *课时学习解锁规则条件：
     * 1. 能力测评通过中级，初级全部解锁。
     * 2. 要解锁课时之前课时所有任务都必须通过。
     * 
     * *访问接口条件：
     * （用户当前岗位 != 该课程所属岗位）或 （用户退出企业（没有岗位））：只能学习已学过的课时。
     * 否则用户可以按正常学习规则解锁
     */
    public function _initialize() {
        parent::_initialize();
        if (empty($this->iUserId)) {
            $this->error("请登录!", -103);
        }
    }

    /**
     * 用户岗位与当前课程岗位是否匹配
     * 防止其他岗位的人根据别人给的链接地址学习别人的岗位课程
     * @param int $iCurriculumId 课程ID
     */
    protected function _isMatchPost($iCurriculumId) {
        $iUserId = $this->iUserId;
        //岗位权限
        if (in_array($this->iRoleId, [1, 2])) {     //[1,2]表示拥有者、管理员
            $arrCateList = M("CategoryAll")->field('cate_id')->where(array('type' => 1))->select();
            foreach ($arrCateList as $val) {
                $arrPostIds[] = $val['cate_id'];
            }
        } else {
            $arrPostIds = [$this->iPostId];
        }

        if (empty($arrPostIds)) {
            return FALSE;
        }
        //当前课程岗位ID
        $cateInfo = M()->table('qy_curriculum c')->field('s.cate_id,c.specialty_id')
                ->join('qy_specialty as s USING(specialty_id)')
                ->where(array('curriculum_id' => $iCurriculumId))
                ->find();
        
        if(!in_array($cateInfo['cate_id'], $arrPostIds)){
            return FALSE;
        }
        //检查该课程的专业是否解锁
        $openLockSpecialtyStatus = M("OpenLock")->field('relat_id,status')->where(array('user_id' => $iUserId, 'type' => 3, 'relat_id' => $cateInfo['specialty_id']))->find();
        if(!empty($openLockSpecialtyStatus)){
            return TRUE;
        }else{
            return FALSE;
        }
    }

    /**
     * 测评结果推荐的专业级别
     * @param int iCateId 岗位ID
     * @return array
     */
    protected function _abilityCheckInfo() {
        $userCheckList = M('UserCheck')->field('cate_id,specialty_sort')->where(array('user_id' => $this->iUserId))->select();
        $cateCheckList = array();
        if ($userCheckList) {
            foreach ($userCheckList as $val) {
                $cateCheckList[$val['cate_id']] = $val['specialty_sort'];
            }
        }
        return $cateCheckList;
    }

    //课程的章节课时列表
    public function lists() {
        $iCurriculumId = $this->getParam('curriculum_id', 0, 'int+', TRUE);
        $iUserId = $this->iUserId;
        $arrChapterList = M('Chapter')->field('chapter_id,chapter_name')->where(array('curriculum_id' => $iCurriculumId, 'status' => 1))->order('sort ASC')->select();
        //first_time 为第一次学习课时的时间日期 NULL表示没学过
        $arrPeriod = M()->table('qy_period p')
                ->field('
                        p.period_id,p.period_name,p.video_duration,p.chapter_id,p.video_url,
                        DATE_FORMAT(MIN(upr.create_time),"%Y-%m-%d") as first_time,
                        IF(MIN(upr.create_time),1,-1) as learned,
                        MAX(pp.total_score) as max_total_score
                ')
                ->join('LEFT JOIN qy_user_period_record as upr ON upr.period_id = p.period_id AND upr.user_id =' . $iUserId)
                ->join('LEFT JOIN qy_paper AS pp ON pp.relat_id = p.period_id AND pp.type = 1 AND pp.status = 1 AND pp.user_id = ' . $iUserId)
                ->where(array('p.curriculum_id' => $iCurriculumId, 'p.status' => 1))
                ->group('p.period_id')
                ->order('p.chapter_id ASC,p.sort ASC')
                ->select();
        
        foreach($arrPeriod as &$val){
            $val['video_url'] = C('SITE_URL').'/video/'.$val['video_url'];
        }
        //如果课程所属岗位与当前用户岗位不匹配，只能学习已经学过的
        $isMatch = $this->_isMatchPost($iCurriculumId);
        if ($isMatch) {
            $arrPeriod = $this->unlockFunc($arrPeriod, $iCurriculumId);
        } else {
            foreach ($arrPeriod as &$val) {
                $val['learned'] = 1;
            }
        }
        /* 为特殊帐号开启所有课时--开始 */
//        if ($iUserId == 93) {
//            foreach ($arrPeriod as &$val) {
//                $val['learned'] = 1;
//            }
//            unset($val);
//        }
        /* 为特殊帐号开启所有课时--结束 */

        foreach ($arrChapterList as &$val) {
            foreach ($arrPeriod as $v) {
                if ($val['chapter_id'] == $v['chapter_id']) {
                    $val['period_list'][] = $v;
                }
            }
        }

        $this->returnList($arrChapterList);
    }

    /**
     * 解锁逻辑过程
     * *课时学习解锁规则条件：
     * 1. 能力测评通过中级，初级全部解锁。
     * 2. 要解锁课时之前课时所有任务都必须通过。
     */
    private function unlockFunc($arrPeriod = array(), $iCurriculumId) {
        $cateCheckList = $this->_abilityCheckInfo(); //用户所有岗位测评结果
        $currData = M()->table('qy_curriculum c')->field('s.sort as specialty_sort,s.cate_id')
                ->join('qy_specialty as s USING(specialty_id)')
                ->where(array('c.curriculum_id' => $iCurriculumId))
                ->find();

        //如果能力测评通过，下面课程、课时 全部解锁。
        if ($currData['specialty_sort'] < intval($cateCheckList[$currData['cate_id']])) {
            foreach ($arrPeriod as $key => &$val) {
                if ($key != 0) {
                    unset($val['video_url']);
                }
                $val['learned'] == -1 && $val['learned'] = '0';
            }
            unset($val);
        } else {
            $first_lock_key = 0;   //列表中出现的第一个锁的key
            $is_open_next_lock = 1;   //是否解锁下节课时 0-否 1-是
            foreach ($arrPeriod as $key => &$val) {
                if (empty($val['first_time'])) {
                    if ($key === 0) { //将第一课时打开
                        $val['learned'] = '0';
                    } else {
                        empty($first_lock_key) && $first_lock_key = $key; //最近要学习（下一个该解锁）的课时key
                    }
                    break;
                } else {
                    if (empty($val['max_total_score']) || 80 > $val['max_total_score']) {    //要解锁下节课时，该课时之前的所有
                        $is_open_next_lock = 0;
                    }
                }
            }
            unset($val);

            if ($first_lock_key && $is_open_next_lock == 1) {
                //规则：要解锁此课时，必须将该课时之前的所有课时任务通过
                $arrPeriod[$first_lock_key]['learned'] = '0';
            }
        }
        return $arrPeriod;
    }

    //章节课时练习列表
    public function chapterPeriodList() {
        $iUserId = $this->iUserId;
        $iCurriculumId = $this->getParam('curriculum_id', 0, 'int+', TRUE);
        $arrChapterList = M('Chapter')->field('chapter_id,chapter_name')->where(array('curriculum_id' => $iCurriculumId, 'status' => 1))->order('sort ASC')->select();
        if (empty($arrChapterList)) {
            $this->success();
        }
        foreach ($arrChapterList as $val) {
            $chapterIds[] = $val['chapter_id'];
        }
        $arrPeriodList = M('Period')->field('period_id,period_name,chapter_id,sort')->where(array('chapter_id' => array('in', $chapterIds), 'status' => 1))->order('sort ASC')->select();
        if (empty($arrPeriodList)) {
            $this->returnList($arrChapterList);
        }
        //已学习过的课时
        $alreadyStudyList = M('UserPeriodRecord')->field('period_id')->where(array('chapter_id' => array('in', $chapterIds), 'user_id' => $iUserId))->group('period_id')->select();
        if (!empty($alreadyStudyList)) {
            foreach ($alreadyStudyList as $val) {
                $alreadyPeriodIds[] = $val['period_id'];
            }
        }
        foreach ($arrPeriodList as &$val) {
            $val['max_total_score'] = 0;
            $val['star_num'] = 0;

            $periodIds[] = $val['period_id'];
            $val['lock_status'] = 0;
            if (in_array($val['period_id'], $alreadyPeriodIds)) {
                $val['lock_status'] = 1;
            }
        }
        unset($val);

        //练习最高分数
        $arrPaperList = M('Paper')->field('relat_id as period_id, MAX(total_score) AS max_total_score')->where(array('relat_id' => array('in', $periodIds), 'user_id' => $iUserId, 'status' => 1, 'type' => 1))->group('relat_id')->select();
        if (!empty($arrPaperList)) {
            foreach ($arrPeriodList as &$val) {
                $val['max_total_score'] = 0;
                $val['star_num'] = 0;
                foreach ($arrPaperList as $vv) {
                    if ($val['period_id'] == $vv['period_id']) {
                        $val['max_total_score'] = $vv['max_total_score'];
                        $val['star_num'] = $this->_starNum($val['max_total_score']);
                    }
                }
            }
        }
        foreach ($arrChapterList as &$val) {
            foreach ($arrPeriodList as $vv) {
                if ($val['chapter_id'] == $vv['chapter_id']) {
                    $val['period_list'][] = $vv;
                }
            }
        }
        unset($val);
        $this->returnList($arrChapterList);
    }

    //课程详情
    public function info() {
        $iCurriculumId = $this->getParam('curriculum_id', 0, 'int+', TRUE);
        $arrWhere['curriculum_id'] = $iCurriculumId;
        $arrWhere['status'] = 1;
        $curriculumInfo = M('Curriculum')->field('curriculum_name, description, target, knowledge')->where(array('curriculum_id' => $iCurriculumId))->find();
        $this->returnList($curriculumInfo);
    }

    //讲师列表
    public function teacherList() {
        $iCurriculumId = $this->getParam('curriculum_id', 0, 'int+', TRUE);
        $teacherList = M()->table('qy_period p')
                ->field('t.teacher_id,t.teacher_name,t.nickname,t.photo,t.description')
                ->join('qy_teacher as t USING(teacher_id)')
                ->where(array('curriculum_id' => $iCurriculumId, 'p.status' => 1))
                ->group('p.teacher_id')
                ->select();
        if (!empty($teacherList)) {
            foreach ($teacherList as &$val) {
                $val['photo'] = C('ADMIN_URL') . $val['photo'];
            }
            unset($val);
        }

        $this->returnList($teacherList);
    }

    //课时详情
    public function periodInfo() {
        $iPeriodId = $this->getParam('period_id', 0, 'int+', TRUE);
        $iUserId = $this->iUserId;
        $arrPeriodInfo = M()->table('qy_period p')->field('p.period_id,p.period_name,p.video_url,p.aliyun_video_id,p.video_duration,p.curriculum_id,p.chapter_id,c.specialty_id')
                ->join('qy_curriculum as c ON c.curriculum_id=p.curriculum_id')
                ->where(array('period_id' => $iPeriodId))
                ->find();

//        $isMatch = $this->_isMatchPost($arrPeriodInfo['curriculum_id']);
//        if (!$isMatch) {
//            $this->returnList($arrPeriodInfo);
//        }

        $iCompanyId = $this->iCompanyId;
        $objUserPeriodRecord = M('UserPeriodRecord');
        //1. 插入学习记录表
        $arrWhere = array(
            'user_id' => $iUserId,
            'company_id' => $iCompanyId,
            'period_id' => $iPeriodId,
            'curriculum_id' => $arrPeriodInfo['curriculum_id'],
            'chapter_id' => $arrPeriodInfo['chapter_id'],
            'post_id' => $this->iPostId,
            'create_time' => array('between', array(date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')))
        );
        $iCount = $objUserPeriodRecord->where($arrWhere)->count();
        
        if ($iCount == 0) {
            $arrData = $arrWhere;
            $arrData['create_time'] = date("Y-m-d H:i:s");
            $objUserPeriodRecord->add($arrData);
        }

        $this->returnList($arrPeriodInfo);
    }

    //获取视频点播凭证
    public function getVideoPlayAuth() {
        $aliyun_video_id = $this->getParam('aliyun_video_id', '', 'string', TRUE);
        import("Org.Util.Aliyun.aliyun-php-sdk-core.Config", '', '.php');
        $regionId = 'cn-shanghai';
        $profile = \DefaultProfile::getProfile($regionId, C('ALIYUN_ACCESS_KEY_ID'), C('ALIYUN_ACCESS_KEY_SECRET'));
        $client = new \DefaultAcsClient($profile);
        $request = new vod\GetVideoPlayAuthRequest();
        $request->setAcceptFormat('JSON');
        $request->setRegionId($regionId);
        $request->setVideoId($aliyun_video_id);            //视频ID
        $authInfo = $client->getAcsResponse($request);
        $jsonAuthInfo = json_decode(json_encode($authInfo, true), true);
        $this->returnList($jsonAuthInfo);
    }
    
}
